import React, {useEffect, useRef, useState} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Image, message, Popconfirm, Switch, TreeSelect} from "antd";
import {
  delGoodsCategory,
  getGoodsCategory,
  setGoodsStatus
} from "@/services/ant-design-pro/goods";
import AddCategory from './components/AddCategory'


const GoodsCategory = () => {
  const actionRef = useRef<ActionType>();
  const [treeData,setTreeData] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [categoryId,setCategoryId] = useState(null);
  useEffect(()=>{
    getGoodsCategory().then(res => {
        setTreeData(res)
    })
  },[])

  const columns: ProColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
      align: 'center',
    },
    {
      title: '分类图标',
      dataIndex: 'image_url',
      search: false,
      align: 'center',
      render: (_, record) => {
        return (
          <Image
            width={50}
            src={record.image_url}
          />
        );
      }
    },
    {
      title: '排序',
      dataIndex: 'weigh',
      search: false,
      align: 'center',
    },

    {
      title: '商品分类',
      dataIndex: 'top_id',
      hideInTable: true,
      search: true,
      width: 100,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <TreeSelect
              style={{width: '100%'}}
              fieldNames-={{ label: 'nickname', key: 'id', children: 'children' }}
              treeData={treeData}
              dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
              placeholder="请选择"
              {...fieldProps}
            />
          );
        }
        return defaultRender(_);
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      filters: true,
      onFilter: true,
      search: true,
      align: 'center',
      valueType: 'select',
      render: (_, record) =>
        <Switch
          checkedChildren="显示"
          unCheckedChildren="隐藏"
          defaultChecked={record.status}
          onChange={async (state) => {
            console.log(state);
            setGoodsStatus({
              id: record.id,
              status: state ? 1 : 0,
            }).then(() => {
              message.success('操作成功！')
              actionRef.current.reload();
            })
          }
          }
        />,
      valueEnum: {
        '1': { text: '显示', status: 'Default' },
        '0': { text: '隐藏', status: 'Processing' },
      },
    },
    {
      title: '分类名称',
      dataIndex: 'nickname',
      search: true,
      align: 'center',
    },

    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={async() => {
            setIsModalVisible(true)
            setCategoryId(record.id)
            }
          }
        >
          编辑
        </a>,
        <Popconfirm
          title="确定要删除规格吗？"
          onConfirm={()=>{
            delGoodsCategory(record.id,{
            }).then(() => {
              message.success('删除成功！')
              actionRef.current.reload();
            })
          }
          }
          onCancel={()=>{
            message.success('已取消');
          }}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>
      ],
    },
  ];
  return (
    <PageContainer
      header={{
        title: '商品分类',
        breadcrumb: {},
      }}
    >
      <ProTable
        style={{paddingTop:'30px'}}
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const data = await getGoodsCategory({...params});
          return {
            data
          }
        }}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle=""
      />
      {isModalVisible ?
        <AddCategory
          isModalVisible={isModalVisible}
          id={categoryId}
          handleCancel={() => {
            setIsModalVisible(false)
          }}
          actionRef={actionRef}
        />
        : null
      }
    </PageContainer>
  );
};

export default GoodsCategory;
